//
//  LoanRecordCell.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/12/25.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SwiftyJSON

@objc protocol LoanRecordCellDelegate {
    @objc optional func changeLoanRecord(loanId:String,status:String) //修改贷款记录
    @objc optional func loanRecordDetails(model:LoanRecordModel) //查看贷款记录详情
    @objc optional func productDetails(model:LoanRecordModel) //查看产品
}

class LoanRecordCell: UITableViewCell {
    
    weak var delegate : LoanRecordCellDelegate?
    
    var model : LoanRecordModel! {
        didSet{
            upDateData()
        }
    }
    
    fileprivate let grayView = UIView()
    fileprivate let amountLabel = UILabel() //贷款金额
    fileprivate let detailsButton = UIButton() //详情
    fileprivate let productLabel = UILabel() //产品
    fileprivate let bankButton = UIButton() //银行
    fileprivate let termLabel = UILabel() //期限
    fileprivate let applyLabel = UILabel() //申请时间
    fileprivate let auditLabel = UILabel() //审核时间
    fileprivate let processBtn = UIButton() //处理中
    fileprivate let lenderBtn = UIButton() //已放款
    fileprivate let finishBtn = UIButton() //已结束
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        grayView.backgroundColor = UIColor.mineColor()
        self.contentView.addSubview(grayView)
        
        amountLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 18))
        grayView.addSubview(amountLabel)
        
        detailsButton.setTitleColor(UIColor.blue, for: .normal)
        detailsButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        detailsButton.addTarget(self, action: #selector(productDetails), for: .touchUpInside)
        grayView.addSubview(detailsButton)
        
        productLabel.textColor = UIColor.gray
        productLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 14))
        grayView.addSubview(productLabel)
        
        bankButton.setTitleColor(UIColor.recordBlue(), for: .normal)
        bankButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 14))
        bankButton.addTarget(self, action: #selector(loanRecordDetails), for: .touchUpInside)
        grayView.addSubview(bankButton)
        
        termLabel.textAlignment = .right
        termLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 14))
        grayView.addSubview(termLabel)
        
        applyLabel.textColor = UIColor.gray
        applyLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 14))
        grayView.addSubview(applyLabel)
        
        auditLabel.textColor = UIColor.gray
        auditLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 14))
        grayView.addSubview(auditLabel)
        
        processBtn.tag = 0
        processBtn.setTitle(processing, for: .normal)
        processBtn.setTitleColor(UIColor.white, for: .normal)
        processBtn.backgroundColor = UIColor.red
        processBtn.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        processBtn.layer.borderColor = UIColor.red.cgColor
        processBtn.layer.borderWidth = 1
        processBtn.layer.cornerRadius = RATIO_H(maxNum: 10)
        processBtn.layer.masksToBounds = true
        processBtn.addTarget(self, action: #selector(changeLoanRecord(sender:)), for: .touchUpInside)
        self.contentView.addSubview(processBtn)
        
        lenderBtn.tag = 1
        lenderBtn.setTitle(toLenders, for: .normal)
        lenderBtn.setTitleColor(UIColor.black, for: .normal)
        lenderBtn.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        lenderBtn.layer.borderColor = UIColor.red.cgColor
        lenderBtn.layer.borderWidth = 1
        lenderBtn.layer.cornerRadius = RATIO_H(maxNum: 10)
        lenderBtn.layer.masksToBounds = true
        lenderBtn.addTarget(self, action: #selector(changeLoanRecord(sender:)), for: .touchUpInside)
        self.contentView.addSubview(lenderBtn)
        
        finishBtn.tag = 2
        finishBtn.setTitle(finished, for: .normal)
        finishBtn.setTitleColor(UIColor.black, for: .normal)
        finishBtn.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        finishBtn.layer.borderColor = UIColor.red.cgColor
        finishBtn.layer.borderWidth = 1
        finishBtn.layer.cornerRadius = RATIO_H(maxNum: 10)
        finishBtn.layer.masksToBounds = true
        finishBtn.addTarget(self, action: #selector(changeLoanRecord(sender:)), for: .touchUpInside)
        self.contentView.addSubview(finishBtn)
        
        let lineView = UIView()
        lineView.backgroundColor = UIColor.lineColor()
        self.contentView.addSubview(lineView)
        
        grayView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(RATIO_H(maxNum: 20))
            make.left.equalToSuperview().offset(RATIO(maxNum: 20))
            make.right.equalToSuperview().offset(RATIO(maxNum: -20))
            make.height.equalTo(RATIO_H(maxNum: 105))
        }
        
        amountLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(RATIO_H(maxNum: 5))
            make.left.equalToSuperview().offset(RATIO(maxNum: 10))
            make.height.equalTo(RATIO_H(maxNum: 30))
            make.width.greaterThanOrEqualTo(10)
        }
        
        detailsButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(amountLabel)
            make.right.equalToSuperview().offset(RATIO(maxNum: -10))
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        productLabel.snp.makeConstraints { (make) in
            make.top.equalTo(amountLabel.snp.bottom).offset(RATIO_H(maxNum: 5))
            make.left.equalTo(amountLabel)
            make.width.greaterThanOrEqualTo(10)
            make.height.equalTo(RATIO_H(maxNum: 20))
        }
        
        termLabel.snp.makeConstraints { (make) in
            make.right.equalTo(detailsButton)
            make.centerY.equalTo(productLabel)
            make.width.greaterThanOrEqualTo(10)
            make.height.equalTo(productLabel)
        }
        
        bankButton.snp.makeConstraints { (make) in
            make.centerY.height.equalTo(productLabel)
            make.left.equalTo(productLabel.snp.right)
            make.width.greaterThanOrEqualTo(10)
        }
        
        applyLabel.snp.makeConstraints { (make) in
            make.top.equalTo(productLabel.snp.bottom)
            make.left.height.equalTo(productLabel)
            make.width.greaterThanOrEqualTo(10)
        }
        
        auditLabel.snp.makeConstraints { (make) in
            make.top.equalTo(applyLabel.snp.bottom)
            make.left.height.equalTo(applyLabel)
            make.width.greaterThanOrEqualTo(10)
        }
        
        processBtn.snp.makeConstraints { (make) in
            make.top.equalTo(grayView.snp.bottom).offset(RATIO_H(maxNum: 15))
            make.left.equalTo(grayView)
            make.height.equalTo(RATIO_H(maxNum: 30))
            make.width.equalTo(RATIO(maxNum: 80))
        }
        
        lenderBtn.snp.makeConstraints { (make) in
            make.centerY.height.width.equalTo(processBtn)
            make.left.equalTo(processBtn.snp.right).offset(RATIO(maxNum: 20))
        }
        
        finishBtn.snp.makeConstraints { (make) in
            make.centerY.height.width.equalTo(lenderBtn)
            make.left.equalTo(lenderBtn.snp.right).offset(RATIO(maxNum: 20))
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 修改贷款记录状态
    @objc fileprivate func changeLoanRecord(sender:UIButton) {
        
        if model.apply_status == "2" || model.apply_status == "\(sender.tag)" {
            return
        }
        
        self.delegate?.changeLoanRecord!(loanId: model.id!, status: "\(sender.tag)")
    }
    
    //MARK: 查看贷款记录
    @objc fileprivate func loanRecordDetails() {
        
        self.delegate?.loanRecordDetails!(model: model)
    }
    
    //MARK: 查看产品详情
    @objc fileprivate func productDetails() {
        
        self.delegate?.productDetails!(model: model)
    }
    
    //MARK: 刷新数据
    fileprivate func upDateData() {
        
        if let detail = model.details as? [String:Any] {
            
            let detailsModel = LoanRecordDetailsModel.setModel(with: detail)
            amountLabel.text = loanAmount + "：" + "\(detailsModel.money ?? "")" + millionYuan
            detailsButton.setTitle(details, for: .normal)
            productLabel.text = loanProduct + "："
            termLabel.text = term + "：" + detailsModel.loan_deadline!
            amountLabel.text = amountLabel.text?.replacingOccurrences(of: "万万", with: million)
        }else {
            amountLabel.text = loanAmount + "：" + "-" + millionYuan
            detailsButton.setTitle(details, for: .normal)
            productLabel.text = loanProduct + "："
            termLabel.text = term + "：" + "-"
        }
        
        applyLabel.text = applicationTime + "：" +  model.create_time!.getDate()
        auditLabel.text = auditTime + "：" + model.change_time!.getDate()
        
        let json = JSON.init(model.recommends ?? Any.self)
        if let recommends = json["list"].arrayObject as? [[String:Any]] {
            if recommends.count == 1 {
                let model = LoanRecordListModel.setModel(with: recommends.first!)
                bankButton.setTitle(model.organization_name! + "-" + model.product_name!, for: .normal)
            }else{
                bankButton.setTitle(toView, for: .normal)
            }
        }else{
            bankButton.setTitle(notProduct, for: .normal)
        }
        
        //已放款
        if model.apply_status! == "1" {
            lenderBtn.setTitleColor(UIColor.white, for: .normal)
            lenderBtn.backgroundColor = UIColor.red
            processBtn.isHidden = true
            
            lenderBtn.snp.remakeConstraints { (make) in
                make.left.centerY.height.width.equalTo(processBtn)
            }
        }else if model.apply_status! == "2" {//已结束
            finishBtn.setTitleColor(UIColor.white, for: .normal)
            finishBtn.backgroundColor = UIColor.red
            processBtn.isHidden = true
            lenderBtn.isHidden = true
            finishBtn.snp.remakeConstraints { (make) in
                make.left.centerY.height.width.equalTo(processBtn)
            }
        }
        
        self.layoutIfNeeded()
        
        if bankButton.frame.maxX > termLabel.frame.origin.x {
            
            productLabel.snp.remakeConstraints { (make) in
                make.top.equalTo(amountLabel.snp.bottom).offset(RATIO_H(maxNum: 5))
                make.left.equalTo(amountLabel)
                make.width.equalTo((productLabel.text?.size(font: RATIO(maxNum: 14), height: RATIO_H(maxNum: 20)).width)!-10)
                make.height.equalTo(RATIO_H(maxNum: 20))
            }
            
            termLabel.snp.remakeConstraints { (make) in
                make.right.equalTo(detailsButton)
                make.centerY.equalTo(productLabel)
                make.width.equalTo((termLabel.text?.size(font: RATIO(maxNum: 14), height: RATIO_H(maxNum: 20)).width)!-8)
                make.height.equalTo(productLabel)
            }
            
            bankButton.snp.remakeConstraints { (make) in
                make.centerY.height.equalTo(productLabel)
                make.left.equalTo(productLabel.snp.right)
                make.right.equalTo(termLabel.snp.left).offset(RATIO(maxNum: -5))
            }
        }
    }

}
